package com.lgl.scsheader.system.service;

import com.lgl.scsapi.base.dao.DaoSupport;
import com.lgl.scsheader.system.model.SysMenu;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Service("menuService")
public class MenuService{

	@Resource(name = "daoSupport")
	private DaoSupport dao;

    /**
     * 通过ID删除菜单
     * @param menuId 菜单ID
     * @return 删除影响的行数
     */
	public int deleteMenuById(String menuId) {
		return dao.delete("SysMenuMapper.deleteMenuById", menuId);
	}

	/**
	 * 保存菜单
	 * @param menu 菜单对象
	 * @return 影响的行数
	 */
	public int saveMenu(SysMenu menu) {
		if (menu == null){
			return -1;
		}
		return dao.save("SysMenuMapper.insertMenu", menu);
	}

	/**
	 * 获取所有的菜单，包括一级和二级菜单
	 * @return 所有的菜单集
	 */
	public List<SysMenu> listAllMenu() {
		List<SysMenu> menuList = (List<SysMenu>) dao.findForList("SysMenuMapper.listAllMenu", null);
		Iterator<SysMenu> menuIterable = menuList.iterator();
		while (menuIterable.hasNext()){
			SysMenu menu = menuIterable.next();
			int parentId = menu.getParentId();
			//如果是1级菜单
			if (parentId == 0){
				continue;
			}
			//如果是子菜单，则添加到对应的父菜单的子菜单集中
			for (SysMenu parentMenu : menuList){
				if (parentId != parentMenu.getMenuId()){
					continue;
				}
				if (parentMenu.getChildrenMenuList() == null){
					parentMenu.setChildrenMenuList(new ArrayList<>(8));
				}
				parentMenu.getChildrenMenuList().add(menu);
				break;
			}
			menuIterable.remove();
		}
		return menuList;
	}

	/**
	 * 编辑菜单
	 * @param menu 菜单对象
	 * @return 更新的行数
	 */
	public int editMenu(SysMenu menu) {
		if (menu == null || menu.getMenuId() == null){
			return -1;
		}
		return dao.update("SysMenuMapper.editMenu", menu);
	}

}
